package com.dtm.client;

import java.lang.reflect.Type;
import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class ConvertPackge {

	private Gson gson = new Gson();

	public byte[] convertToByte(Object data, int code) {

		return (code + gson.toJson(data)).getBytes();
	}

	public int getCode(byte[] bytes) {
		String data = new String(bytes);
		int code = Integer.parseInt("" + data.charAt(0));
		return code;
	}

	public String getJsonData(byte[] bytes) {
		String data = new String(bytes);
		String jsonData = "";
		for (int i = 1; i < data.length(); i++) {
			jsonData += data.charAt(i);
		}
		return jsonData;
	}

	public ArrayList<Client> jsonToArraylist(String jsonData) {
		Type collectionType = new TypeToken<ArrayList<Client>>() {
		}.getType();
		ArrayList<Client> listJson = gson.fromJson(jsonData, collectionType);
		return listJson;
	}

	public Client jsonToClient(String jsonData) {
		Client client = gson.fromJson(jsonData, Client.class);
		return client;
	}

	public Object convertTobyte(byte[] bytes) {
		String data = new String(bytes);
		int code = Integer.parseInt("" + data.charAt(0));
		String jsonData = "";
		for (int i = 1; i < data.length(); i++) {
			jsonData += data.charAt(i);
		}
		if (code == ClientThread.LIST) {
			Type collectionType = new TypeToken<ArrayList<Client>>() {
			}.getType();
			ArrayList<Client> listJson = gson
					.fromJson(jsonData, collectionType);
			return listJson;
		} else if (code == ClientThread.REG) {
			String name = gson.fromJson(jsonData, String.class);
			return name;
		} else if (code == ClientThread.UDL) {
			Client newClient = gson.fromJson(jsonData, Client.class);
			return newClient;
		} else {
			return null;
		}

		// switch (code) {
		// case REG:
		// String name;
		// name = gson.fromJson(jsonData, String.class);
		// break;
		// case UDL:
		//
		// break;
		// case STR:
		//
		// break;
		// default:
		// break;
		// }
	}
}
